package orm

import (
	"database/sql"
	"fmt"
)

type OrmContext struct {
	db *sql.DB
}

func NewOrmContext(driver, source string) (e *OrmContext, err error) {
	db, err := sql.Open(driver, source)
	if err != nil {
		fmt.Errorf("%s", err)
		return
	}
	// Send a ping to make sure the database connection is alive.
	if err = db.Ping(); err != nil {
		fmt.Errorf("%s", err)
		return
	}
	e = &OrmContext{db: db}
	fmt.Println("Connect database success")
	return
}

func (OrmContext *OrmContext) Close() {
	if err := OrmContext.db.Close(); err != nil {
		fmt.Errorf("%s", err)
	}
	fmt.Println("Close database success")
}

func (OrmContext *OrmContext) NewSession() *Session {
	return New(OrmContext.db)
}
